using UnityEngine;
using UnityEngine.UI;

namespace Super
{
    [RequireComponent(typeof(CanvasRenderer))]
    public class RadarFG : Graphic
    {
        public enum ForegroundType
        {
            None,       // 无背景
            Circular,    // 圆形划分背景
            Polygonal    // 多边形划分背景
        }

        [Header("Foreground Type")]
        public ForegroundType foregroundType = ForegroundType.Polygonal;

        [Header("Main Settings")]
        public float length = 100f;          // 最大半径长度
        public int segments = 5;             // 边数/顶点数(五边形)
        public int divisions = 5;            // 划分层级数
        public float offsetRotate = 0f;      // 旋转偏移角度
        public float lineThickness = 2f;     // 线条粗细

        [Header("Colors")]
        public Color axesColor = new Color(1, 1, 1, 0.5f);       // 轴线颜色
        public Color divisionColor = new Color(1, 1, 1, 0.2f);   // 分级线颜色

        [Header("Circular Settings")]
        [Tooltip("圆形平滑度(仅圆形背景使用)")]
        public int circleSegments = 60;      

        protected override void OnPopulateMesh(VertexHelper vh)
        {
            vh.Clear();

            if (foregroundType == ForegroundType.None)
            {
                // 不绘制任何内容
                return;
            }

            switch (foregroundType)
            {
                case ForegroundType.Circular:
                    DrawCircularForeground(vh);
                    break;
                case ForegroundType.Polygonal:
                    DrawPolygonalForeground(vh);
                    break;
            }
        }

        private void DrawCircularForeground(VertexHelper vh)
        {
            // 绘制分级圆形
            for (int div = 1; div <= divisions; div++)
            {
                float currentRadius = (length / divisions) * div;
                DrawCircle(vh, currentRadius, divisionColor);
            }

            // 绘制轴线
            for (int i = 0; i < segments; i++)
            {
                float angle = offsetRotate + (360f / segments) * i;
                Vector2 endPoint = GetPointOnCircle(length, angle);
                DrawLine(vh, Vector2.zero, endPoint, axesColor);
            }
        }

        private void DrawPolygonalForeground(VertexHelper vh)
        {
            // 绘制分级多边形
            for (int div = 1; div <= divisions; div++)
            {
                float currentRadius = (length / divisions) * div;
                DrawPolygon(vh, currentRadius, divisionColor);
            }

            // 绘制轴线
            for (int i = 0; i < segments; i++)
            {
                float angle = offsetRotate + (360f / segments) * i;
                Vector2 endPoint = GetPointOnPolygon(length, angle);
                DrawLine(vh, Vector2.zero, endPoint, axesColor);
            }
        }

        // 绘制圆形
        private void DrawCircle(VertexHelper vh, float radius, Color color)
        {
            for (int i = 0; i < circleSegments; i++)
            {
                float angle1 = Mathf.Deg2Rad * (i * 360f / circleSegments);
                float angle2 = Mathf.Deg2Rad * ((i + 1) * 360f / circleSegments);
                
                Vector2 point1 = GetPointOnCircle(radius, angle1 * Mathf.Rad2Deg);
                Vector2 point2 = GetPointOnCircle(radius, angle2 * Mathf.Rad2Deg);
                
                DrawLine(vh, point1, point2, color);
            }
        }

        // 绘制多边形
        private void DrawPolygon(VertexHelper vh, float radius, Color color)
        {
            for (int i = 0; i < segments; i++)
            {
                float angle1 = offsetRotate + (360f / segments) * i;
                float angle2 = offsetRotate + (360f / segments) * ((i + 1) % segments);
                
                Vector2 point1 = GetPointOnPolygon(radius, angle1);
                Vector2 point2 = GetPointOnPolygon(radius, angle2);
                
                DrawLine(vh, point1, point2, color);
            }
        }

        // 绘制中心填充多边形
        private void DrawCenterPolygon(VertexHelper vh, Color color)
        {
            if (segments < 3) return;

            Vector2[] points = new Vector2[segments];

            // 收集所有顶点
            for (int i = 0; i < segments; i++)
            {
                float angle = offsetRotate + (360f / segments) * i;
                points[i] = GetPointOnPolygon(length / divisions, angle);
            }

            // 创建三角形扇
            for (int i = 1; i < segments - 1; i++)
            {
                vh.AddVert(points[0], color, Vector2.zero);
                vh.AddVert(points[i], color, Vector2.zero);
                vh.AddVert(points[i + 1], color, Vector2.zero);
                
                int baseIndex = i * 3;
                vh.AddTriangle(baseIndex, baseIndex + 1, baseIndex + 2);
            }
        }

        // 绘制线条(带厚度)
        private void DrawLine(VertexHelper vh, Vector2 start, Vector2 end, Color color)
        {
            Vector2 direction = (end - start).normalized;
            Vector2 perpendicular = new Vector2(-direction.y, direction.x) * lineThickness * 0.5f;
            
            UIVertex[] vertices = new UIVertex[4];
            
            vertices[0].position = start - perpendicular;
            vertices[1].position = start + perpendicular;
            vertices[2].position = end + perpendicular;
            vertices[3].position = end - perpendicular;
            
            for (int i = 0; i < 4; i++)
            {
                vertices[i].color = color;
                vertices[i].uv0 = Vector2.zero;
            }
            
            vh.AddUIVertexQuad(vertices);
        }

        // 获取圆形上的点
        private Vector2 GetPointOnCircle(float radius, float angleDegrees)
        {
            float angleRad = Mathf.Deg2Rad * angleDegrees;
            return new Vector2(
                radius * Mathf.Sin(angleRad),
                radius * Mathf.Cos(angleRad)
            );
        }

        // 获取多边形上的点
        private Vector2 GetPointOnPolygon(float radius, float angleDegrees)
        {
            return GetPointOnCircle(radius, angleDegrees);
        }

        // 当脚本参数改变时刷新
        protected override void OnValidate()
        {
            base.OnValidate();
            if (IsActive())
            {
                SetVerticesDirty();
            }
        }

        // 公开方法：动态切换背景类型
        public void SetForegroundType(ForegroundType type)
        {
            foregroundType = type;
            SetVerticesDirty();
        }

        // 公开方法：完全隐藏背景
        public void HideForeground()
        {
            SetForegroundType(ForegroundType.None);
        }

        // 公开方法：显示背景（默认为多边形）
        public void ShowForeground(ForegroundType type = ForegroundType.Polygonal)
        {
            SetForegroundType(type);
        }
    }
}